///////////////////////
// constants

var DHTML = (document.getElementById || document.all || document.layers);
var NR_SEARCH_RESULTS = 10;
var NR_TOP_LIST_ENTRIES = 10;

///////////////////////
// globals

var nrInitLoads = 0;
var searchRaces_array = null;
var stations_array = null;
var topListRaces_array = null;

var search_firstName = null;
var search_lastname = null;
var search_club = null;
var search_startNumber = null;
var search_race = null;
var search_start = null;
var search_totalHits = null;

var map = null;
var mapCenterX = null;
var mapCenterY = null;

var lang = _args()["lang"];
if (typeof lang == "undefined") {
  lang = "en";
}

//year = 2007; console.warn( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! USING TEST YEAR " + year + " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
//var year = 2008;
var year = 2009;

///////////////////////////////////
// ONLOAD
//////////////////////////////////

if ( DHTML ) {
    window.onload = init;
    window.onresize = onResize_;
}

function init()
{
    // send to analytics
    _IG_Analytics( "UA-3565718-1", "/vasaloppet-gadget/onload" );

    var prefs = new _IG_Prefs();
    
    nrInitLoads = 3;

    // load stations
    _IG_FetchContent( prefs.getString( "GADGET_BASE_URL" ) + prefs.getString( "STATIONS_URL" ), onLoad_stations );

    // load races for top list
    _IG_FetchContent( prefs.getMsg( "TOP_LIST_RACES_URL" ) + "&year=" + year, onLoad_topListRaces );

    // load races for search form
    _IG_FetchContent( prefs.getMsg( "SEARCH_RACES_URL" ), onLoad_searchRaces );
}


///////////////////////////////////

function build_news( newsItems_array )
{
    var divs_array = _gel( "page_news" ).getElementsByTagName( "div" );

    var feedCount = 0;
    for ( var loop = 0; loop < divs_array.length; loop++ ) {
	var div = divs_array[loop];

	makeClassHandler( div );
	if ( div.hasClass( "newsItem" ) ) {
	    toggleVisibility( div, true );

	    var ni = newsItems_array[feedCount];

	    var p_array = div.getElementsByTagName( "p" );
	
	    if ( ni.Date != undefined ) {
		var date = new Date( ni.Date * 1000 );
		var month = ( date.getMonth() + 1 );
		if ( month < 10 ) {
		    month = "0" + month;
		}
		var day = date.getDate();
		if ( day < 10 ) {
		    day = "0" + day;
		}
		
		p_array[0].innerHTML = date.getFullYear() + "-" + month + "-" + day;
	    }
	    p_array[1].innerHTML = controlExternalValue( ni.Title );

	    var link = p_array[2].getElementsByTagName( "a" )[0];

	    if ( ni.Link != undefined ) {
		link.href = ni.Link;
	    }
	    else {
		link.onclick = function() { return false; }
	    }

	    feedCount++;
	}
    }
}

function build_profile( param_profile )
{
    var p = param_profile;
    var prefs = new _IG_Prefs();

    var profilePage = _gel( "page_profile" );

    var h3 = profilePage.getElementsByTagName( "h3" )[0];
    h3.innerHTML = controlExternalValue( p.firstName ) + " " + controlExternalValue( p.lastName );

    var statDivs_array = _gel( "statsList" ).getElementsByTagName( "div" );
    statDivs_array[0].innerHTML = "<span>" + prefs.getMsg( "profile_startNumber" ) + ":</span> " + controlExternalValue( p.startNumber );
    statDivs_array[1].innerHTML = "<span>" + prefs.getMsg( "profile_club" ) + ':</span> ' + controlExternalValue( p.club, '<a href="#" class="club_' + p.club + '" id="clubSearchLink">' + p.club + "</a>" );
    statDivs_array[2].innerHTML = "<span>" + prefs.getMsg( "profile_raceTime" ) + ":</span> " + controlExternalValue( p.raceTime );
    statDivs_array[3].innerHTML = "<span>" + prefs.getMsg( "profile_avgSpeed" ) + ":</span> " + controlExternalValue( p.avgSpeed, ( Math.round( p.avgSpeed * 10 ) / 10 ) ) + " km/h";
    statDivs_array[4].innerHTML = "<span>" + prefs.getMsg( "profile_position" ) + ":</span> " + controlExternalValue( p.position );


    var csl = _gel( "clubSearchLink" );
    if ( csl ) {
	csl.ref = this;
	csl.onclick = function() {
	    this.ref.onClick_clubSearchLink( this.className );
	    return false;
	}
    }


    var table = "<table><tbody>";
    table += '<tr><th></th><th class="time">' + prefs.getMsg( "profile_time" ) + '</th><th class="position">' + prefs.getMsg( "profile_position" ) + '</th><th class="speed">km/h</th></tr>';
    

    var stationList = new Array();
    var startStation = getStationNameById( p.stationList[0].station - 1 );

    if ( startStation ) {
	stationList.push( { station: ( p.stationList[0].station - 1 ), raceTime: "00:00:00" } );
    }

    stationList = stationList.concat( p.stationList );

    for ( var loop = 0; loop < stationList.length; loop++ ) {
	var s = stationList[loop];
	var row = "";

	var station = controlExternalValue( getStationNameById( s.station ) );

	row += '<tr class="' + ( loop % 2 ? '' : 'uneven' ) + ( loop == 0 ? ' first' : '' ) + '"><td class="station">' + station + '</td><td>' + controlExternalValue( s.raceTime ) + '</td><td>' + controlExternalValue( s.position ) + '</td><td>' + controlExternalValue( s.speed ) + '</td></tr>';
	
	table += row;
    }

    table += "</tbody></table>";

    var list = _gel( "stationsList" );
    list.innerHTML = table;
}

function build_search( param_results )
{
    search_start = param_results.start;
    search_totalHits = param_results.totalHits;

    var table = "<table><tbody>";

    for ( var loop = 0; loop < param_results.searchResults.length; loop++ ) {
	var r = param_results.searchResults[loop];

	var row = "";

	row += '<tr class="' + ( loop % 2 ? '' : 'uneven' ) + ( loop == 0 ? ' first' : '' ) + '"><td class="place">' + ( loop + search_start ) + '.</td><td><a href="#" class="profileLink" id="profile' + r.oid + '">' + r.firstName + " " + r.lastName + '</a></td></tr>';
	
	table += row;
    }
    var lastIndex = ( loop + search_start - 1 );

    table += "</tbody></table>";

    var list = _gel( "searchList" );
    list.innerHTML = table;
    
    initProfileLinks();

    // paging
    var btnPrev = _gel( "searchButtonPrev" );
    var btnNext = _gel( "searchButtonNext" );

    if ( Math.floor( search_start / NR_SEARCH_RESULTS ) > 0 ) {
	btnPrev.dropClass( "inactivePrev" );
    }
    else {
	btnPrev.addClass( "inactivePrev" );
    }

    if ( Math.floor( search_start / NR_SEARCH_RESULTS ) < Math.floor( search_totalHits / NR_SEARCH_RESULTS ) ) {
	btnNext.dropClass( "inactiveNext" );
    }
    else {
	btnNext.addClass( "inactiveNext" );
    }

    var pagesContainer = _gel( "pages" );
    pagesContainer.innerHTML = search_start + " - " + lastIndex + " (<em>" + search_totalHits + "</em>)";

}

function build_topList( topList_array )
{
    var prefs = new _IG_Prefs();

    var table = "<table><tbody>";

    for ( var loop = 0; loop < topList_array.length; loop++ ) {
	var ti = topList_array[loop];
	var row = "";

	row += '<tr class="' + ( loop % 2 ? '' : 'uneven' ) + ( loop == 0 ? ' first' : '' ) + '"><td class="place">' + ( loop + 1 ) + '.</td><td><a href="' + ti.profileUrl + '" class="profileLink">' + ti.firstName + " " + ti.lastName + '</a></td><td class="time">';
	
	if ( loop == 0 ) {
	    row += controlExternalValue( ti.raceTime );
	}
	else {
	    row += controlExternalValue( ti.timeDiff, '(+ ' + ti.timeDiff + ')' );
	}

	row += '</td></tr>';
	table += row;
    }

    table += "</tbody></table>";

    var list = _gel( "raceList" );
    list.innerHTML = table;

    initProfileLinks();
}

function build_weather( weather_array )
{
    var prefs = new _IG_Prefs();

    var divs_array = _gel( "page_weather" ).getElementsByTagName( "div" );

    var feedCount = 0;
    for ( var loop = 0; loop < divs_array.length; loop++ ) {
	var div = divs_array[loop];

	makeClassHandler( div );
	if ( div.hasClass( "weatherItem" ) ) {
	    toggleVisibility( div, true );

	    var wi = weather_array[feedCount];

	    // correct image and information
	    var img = div.getElementsByTagName( "img" )[0];

	    var imagesURL = prefs.getString( "GADGET_BASE_URL" ) + prefs.getString( "IMAGES_URL" );
	    if ( wi.weather != undefined ) {
		toggleVisibility( img, true );
		img.src = imagesURL + "weather" + wi.weather + ".gif";
		img.alt = controlExternalValue( wi.desc );
		img.title = controlExternalValue( wi.desc );
	    }

	    // which station
	    var h2 = div.getElementsByTagName( "h2" )[0];
	    h2.innerHTML = controlExternalValue( wi.station, getStationNameById( wi.station ) );

	    // weather stats
	    var p_array = div.getElementsByTagName( "p" );

	    /* SNOW TEMP ACTIVE
	    p_array[0].innerHTML = "<span>" + prefs.getMsg( "weather_airTemp" ) + ":</span> " + controlExternalValue( wi.temp, ( wi.temp + "&deg;C" ) );
	    p_array[1].innerHTML = "<span>" + prefs.getMsg( "weather_snowTemp" ) + ":</span> " + controlExternalValue( wi["temp-snow"], ( wi["temp-snow"] + "&deg;C" ) );
	    p_array[2].innerHTML = "<span>" + prefs.getMsg( "weather_wind" ) + ":</span> " + controlExternalValue( wi["wind-str"] ) + " " + controlExternalValue( wi["wind-dir"], prefs.getMsg( "weather_wind_" + wi["wind-dir"] ) ) + " m/s";
		*/
		
	    /* SNOW TEMP INACTIVE */
	    p_array[0].innerHTML = "<span>" + prefs.getMsg( "weather_airTemp" ) + ":</span> " + controlExternalValue( wi.temp, ( wi.temp + "&deg;C" ) );
	    p_array[1].innerHTML = "<span>" + prefs.getMsg( "weather_wind" ) + ":</span> " + controlExternalValue( wi["wind_str"], wi["wind_str"].replace(".", ",") ) + " " + controlExternalValue( wi["wind_dir"], prefs.getMsg( "weather_wind_" + wi["wind_dir"] ) ) + " m/s";
	    p_array[2].innerHTML = "<span></span>";
		
	    feedCount++;
	}
    }

}

function centerLoader()
{
    var loader = _gel( "throbber" );

    if ( loader ) {
	var contentWidth = _gel( "contentHolder" ).offsetWidth;
	loader.style.width = ( contentWidth - ( loader.offsetLeft * 2 ) ) + "px";
    }
}

function centerMap()
{
    if ( map != null ) {
	map.checkResize();
	
	if ( mapCenterX == null || mapCenterY == null) {
	    var maxX = null;
	    var maxY = null;
	    var minX = null;
	    var minY = null;
	    
	    // find border values for longitude and latitude
	    for ( var loop = 0; loop < stations_array.length; loop++ ) {
		var s = stations_array[loop];

		// skip station "Klockstapeln"
 		if( s.id == 9 ) {
		    continue;
		}

		var pos = s.position.split(",");
		var y = pos[0];
		var x = pos[1];

		if ( maxX == null || x > maxX ) {
		    maxX = x;
		}
		if ( maxY == null || y > maxY ) {
		    maxY = y;
		}

		if ( minX == null || x < minX ) {
		    minX = x;
		}
		if ( minY == null || y < minY ) {
		    minY = y;
		}
	    }
	    
	    mapCenterX = parseFloat( minX ) + parseFloat( ( maxX - minX ) / 2 );
	    mapCenterY = parseFloat( minY ) + parseFloat( ( maxY - minY ) / 2 );
	}

	map.setCenter( new GLatLng( mapCenterY, mapCenterX ), 8 );
    }
}

function clearSearchForm()
{
    var form = _gel( "searchForm" );

    // clear all text inputs
    var inputs_array = form.getElementsByTagName( "input" );
    for ( var loop = 0; loop < inputs_array.length; loop++ ) {
	var i = inputs_array[loop];
	
	if ( i.hasClass( "inputText" ) ) {
	    i.value = "";
	}
    }

    // reset race select
    _gel( "searchRaceSelect" ).selectedIndex = 0;

    // also hide previous search results, and show clear div
    toggleVisibility( _gel( "searchClear" ), true );
    toggleVisibility( _gel( "searchList" ), false );
    toggleVisibility( _gel( "searchBottomBar" ), false );
    toggleVisibility( _gel( "noSearchResults" ), false );
}

function controlExternalValue( param_value, param_output )
{
    if ( param_value == undefined || param_value.length == 0 ) {
	return "-";
    }
    else {
	if ( param_output != undefined ) {
	    return param_output;
	}
	else {
	    return param_value;
	}
    }
}

function createMapMarker(point, index, iconImage, s, u) 
{
    var width;
    var height;

    switch(iconImage) {
    case "map_start_end":
	height = width = 20;
	break;
    case "map_bluering":
    case "map_light_bluering":
	height = width = 14;
	break;
    case "map_bluering_current":
	height = 29;
	width = 14;
	break;
    }

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    baseIcon = new GIcon();
    baseIcon.shadow = "";
    baseIcon.iconSize = new GSize( width, height );
    baseIcon.iconAnchor = new GPoint( Math.round( width / 2 ), Math.round( height / 2 ) );
/*
    baseIcon.iconAnchor = new GPoint(gp,gp);
    baseIcon.infoWindowAnchor = new GPoint(gp,gp);
    baseIcon.infoShadowAnchor = new GPoint(gp,gp); 
*/

    // Create a lettered icon for this point using our icon class
    var customIcon = new GIcon(baseIcon);
    var prefs = new _IG_Prefs();
    var imagesURL = prefs.getString( "GADGET_BASE_URL" ) + prefs.getString( "IMAGES_URL" );
    customIcon.image = imagesURL + iconImage + ".png";
    
    // Set up our GMarkerOptions object
    var markerOptions = { icon:customIcon };
    var marker = new GMarker(point, markerOptions );

    return marker;
}

function doSearch( param_start, param_firstName, param_lastname, param_club, param_startNumber, param_race )
{
    if ( param_firstName != undefined ) {
	search_firstName = param_firstName;
    }

    if ( param_lastname != undefined ) {
	search_lastname = param_lastname;
    }

    if ( param_club != undefined ) {
	search_club = param_club;
    }

    if ( param_startNumber != undefined ) {
	search_startNumber = param_startNumber;
    }

    if ( param_race != undefined ) {
	search_race = param_race;
    }
    
    var url = new _IG_Prefs().getMsg( "SEARCH_URL" );
    url += "&firstName=" + _esc( search_firstName );
    url += "&lastName=" + _esc( search_lastname );
    url += "&club=" + _esc( search_club );
    url += "&startNumber=" + _esc( search_startNumber );
    url += "&race=" + search_race;
    url += "&start=" + param_start;
    url += "&year=" + year;
    url += "&maxHits=" + 10;

    showLoader();
    _IG_FetchContent( url, onLoad_search );
}

function drawRaceMap( param_currentStationId ) 
{
    map.clearOverlays();

    var polyPassed_array = new Array();
    var polyLeft_array = new Array();
    var rowsPrinted = 0;

    var currentStationId = param_currentStationId || 1;

    var hasPassedCurrentStation = false;

    // Use station just before "Klockstapeln"
    if ( currentStationId == 9 ) {
	currentStationId = 8;
    }

    if ( GBrowserIsCompatible() ) {
	for ( var i = 0; i < stations_array.length; i++ ) {
	    var s = stations_array[i];

	    // skip station "Klockstapeln"
 	    if( s.id == 9 ) {
		continue;
	    }

	    var pos = s.position.split(",");
	    var latlng = new GLatLng(pos[0],pos[1]);

	    if ( hasPassedCurrentStation ) {
		polyLeft_array.push( latlng );
	    }
	    else {
		polyPassed_array.push( latlng );
	    }
	    
	    if( i == 0 || i == ( stations_array.length - 1 ) ) {
		var iconName = "map_start_end";
	    } 
	    else {
		if ( s.id == currentStationId ) {
		    var iconName = "map_bluering_current";
		}
		else if ( hasPassedCurrentStation ) {
		    var iconName = "map_light_bluering";
		}
		else {
		    var iconName = "map_bluering";
		}
	    }

	    map.addOverlay( createMapMarker( latlng, i, iconName, s ) );

	    if ( s.id == currentStationId ) {
		hasPassedCurrentStation = true;
		polyLeft_array.push( latlng );
	    }
	}

	map.addOverlay( new GPolyline( polyPassed_array, "#1b2563", 3, 1 ) );
	map.addOverlay( new GPolyline( polyLeft_array, "#7c90ac", 3, 1 ) );
    } 
}

function getJSONFromFetch( param_response, param_caller )
{
    if ( param_response == null ) {
        showError( param_caller + ": no response" );
        return null;
    }

    try {
	var j = param_response.parseJSON();
	return j;
    }
    catch ( e ) {
	// not parseable json
        showError( param_caller + ": non parseable json " + e );
	console.error( param_response );
	return null;
    }
}

function getLastPage()
{
    var ret = parseInt( new _IG_Prefs(). getString( "lastPage" ) );

    if ( isNaN( ret ) ) {
	return 0;
    }

    return ret;
}

function getLastRace()
{
    var ret = parseInt( new _IG_Prefs(). getString( "lastRace" ) );

    if ( isNaN( ret ) ) {
	return 0;
    }

    return ret;
}

function getStationById( param_id )
{
    for ( var loop = 0; loop < stations_array.length; loop++ ) {
	var s = stations_array[loop];

	if ( s.id == param_id ) {
	    return s;
	}
    }

    return null;
}

function getStationNameById( param_id )
{
    var s = getStationById( param_id );

    if ( s ) {
	return s.name;
    }
    else {
	return null;
    }
}

function hideLoader()
{
    var throbber = _gel( "throbber" );
    toggleVisibility( throbber, false );
}

function initMainMenu()
{
    var tabMenuLis_array = _gel( "mainMenu" ).getElementsByTagName( "li" );
    for ( var loop = 0; loop < tabMenuLis_array.length; loop++ ) {
	var li = tabMenuLis_array[loop];
	makeClassHandler( li );

	var a = li.getElementsByTagName( "a" )[0];

	a.ref = this;
	a._id = loop;
	a.onclick = function() {
	    this.ref.onClick_menuTab( this._id );
	    return false;
	}
    }
}

function initMap()
{
    // init map
    if ( GBrowserIsCompatible() ) {
	if ( map == null ) {
            map = new GMap2( _gel( "map" ) );
	    centerMap();

//	    map.addControl( new GSmallZoomControl() );
	    map.addControl( new GSmallMapControl() );
	}
    }    
}

function initNewSearchButton()
{
    var newSearchButton = _gel( "profileButtonPrev" );
    newSearchButton.ref = this;
    newSearchButton.onclick = function() {
	this.ref.clearSearchForm();
	this.ref.showPage( 3 );
    }
}

function initProfileLinks()
{
    var as_array = _gelstn( 'a' );

    for ( var loop = 0; loop < as_array.length; loop++ ) {
	var a = as_array[loop];

	makeClassHandler( a );
	if ( a.hasClass( "profileLink" ) ) {

	    a.ref = this;
	    a.onclick = function() {
		if ( this.id ) {
		    this.ref.onClick_profileLink( this.id );
		}
		else {
		    this.ref.onClick_profileDirectLink( this.href );
		}
		
		return false;
	    }
	}
    }
}

function initRaceSelect( param_lastRace )
{
    var select = _gel( "raceSelect" );

    select.ref = this;
    select.onchange = function( param ) {
	this.ref.onChange_raceSelect();
	return false;
    }

    // add options
    var nrLoops = topListRaces_array.length;
    for ( var loop = 0; loop < nrLoops; loop++ ) {
	var ri = topListRaces_array[loop];
	
	var option = document.createElement( "option" );
	option.text = ri.raceName;
	option.value = ri.raceId;
	
	try {
	    select.add( option, null ); // standards compliant
	}
	catch( ex ) {
	    select.add( option ); // IE only
	}
    }

    // select option from last session
    try {
	select.selectedIndex = param_lastRace;
    }
    catch ( ex ) {
	console.error( "initRaceSelect: no souch index: " + param_lastRace );
    }
}

function initSearchForm()
{
    var form = _gel( "searchForm" );
    
    form.ref = this;
    form.onsubmit = function() {
	this.ref.onSubmit_searchForm();
	return false;
    }

    // add listeners to form and all inputs
    form.ref = this;
    form.onkeyup = function() {
	this.ref.onKeyUp_form();
    }

    var inputs_array = form.getElementsByTagName( "input" );
    for ( var loop = 0; loop < inputs_array.length; loop++ ) {
	var i = inputs_array[loop];
	makeClassHandler( i );

	if ( i.hasClass( "inputText" ) ) {
	    i.ref = this;
	    i.onchange = function() {
		this.ref.onChange_searchInput( this );
	    }
	}
    }

    // paging
    var btnPrev = _gel( "searchButtonPrev" );
    var btnNext = _gel( "searchButtonNext" );

    makeClassHandler( btnPrev );
    makeClassHandler( btnNext );

    btnPrev.ref = this;
    btnPrev.onclick = function() {
	if( !this.hasClass( "inactivePrev" ) ) {
	    this.ref.onClick_searchButtonPrev();
	}
	return false;
    }

    btnNext.ref = this;
    btnNext.onclick = function() {
	if ( !this.hasClass( "inactiveNext" ) ) {
	    this.ref.onClick_searchButtonNext();
	}
	return false;
    }

    updateSearchSubmit();
}

function initSearchSelect()
{
    var select = _gel( "searchRaceSelect" );

    // add options
    var nrLoops = searchRaces_array.length;
    for ( var loop = 0; loop < nrLoops; loop++ ) {
	var ri = searchRaces_array[loop];

	// see if the race is is happening this year
	for ( var yearLoop = 0; yearLoop < ri.yearList.length; yearLoop++ ) {
	    if ( ri.yearList[yearLoop] == year ) {

		var option = document.createElement( "option" );
		option.text = ri.raceName;
		option.value = ri.raceId;
		
		try {
		    select.add( option, null ); // standards compliant
		}
		catch( ex ) {
		    select.add( option ); // IE only
		}

		break;
	    }
	}
    }
}

function isSearchFormEmpty()
{
    var inputs_array = _gel( "searchForm" ).getElementsByTagName( "input" );
    for ( var loop = 0; loop < inputs_array.length; loop++ ) {
	var i = inputs_array[loop];

	if ( i.hasClass( "inputText" ) ) {
	    if ( i.value.length > 0 ) {
		return false;
	    }
	}
    }
    
    return true;
}

function loadContent_news()
{
    showLoader();
    var url = new _IG_Prefs().getMsg( "NEWS_URL" );
    _IG_FetchFeedAsJSON( url, onLoadContent_news, 4, false );
}

function loadContent_profile( param_url )
{
    hideAllPages();
    toggleVisibility( _gel( "page_profile" ), true );
    lastPage = null;
    new _IG_Prefs().set( "lastPage", lastPage );
    updateMainMenu( 3 );

    showLoader();
		var url = param_url;
		_IG_FetchContent( url, onLoadContent_profile );
}

function loadContent_topList( param_raceID )
{
    var url = new _IG_Prefs().getMsg( "TOP_LIST_URL" );
    url += "&year=" + year + "&raceSelection=" + param_raceID + "&length=" + NR_TOP_LIST_ENTRIES;

    showLoader();

    _IG_FetchContent( url, onLoadContent_topList );
}

function loadContent_weather()
{
    var url = new _IG_Prefs().getMsg( "WEATHER_URL" );
    showLoader();
    _IG_FetchContent( url, onLoadContent_weather );
}

function onChange_searchInput( param_input )
{
    updateSearchSubmit();
}

function onClick_clubSearchLink( param_class )
{
    var clubStr = param_class.split( "_" )[1];
    
    if ( clubStr ) {
	clearSearchForm();
	_gel( "club" ).value = clubStr;
	showPage( 3 );
	onSubmit_searchForm();    
    }
}

function onClick_menuTab( param_tabID )
{
    var lastPage = getLastPage();
    
    if ( param_tabID != lastPage ) {
	updateMainMenu( param_tabID );

	showPage( param_tabID );
    }
}

function onClick_profileLink( param_id )
{
    var oid = param_id.split( "profile" )[1];

    if ( oid ) {
	var url = new _IG_Prefs().getMsg( "PROFILE_URL" );
	url += "&year=" + year + "&oid=" + oid;
	
	loadContent_profile( url );
    }
}

function onClick_profileDirectLink( param_url )
{
    loadContent_profile( param_url );
}

function onClick_searchButtonNext()
{
    doSearch( search_start + NR_SEARCH_RESULTS );
}

function onClick_searchButtonPrev()
{
    doSearch( search_start - NR_SEARCH_RESULTS );
}

function onChange_raceSelect()
{
    var select = _gel( "raceSelect" );
    var index = select.selectedIndex;
    var value = select.getElementsByTagName( "option" )[index].value;
    
    var lastRace = getLastRace();

    if ( index != lastRace ) {
	var prefs = new _IG_Prefs();
	prefs.set( "lastRace", index );

	updateTopList();
    }
}

function onKeyUp_form()
{
    updateSearchSubmit();
}

function onLoad_search( param_response ) 
{
    hideLoader();

    var j = getJSONFromFetch( param_response, "onLoad_search" );

    toggleVisibility( _gel( "searchClear" ), false );

    if ( j != null && j.totalHits != undefined ) {
	if ( j.totalHits < 1 || j.searchResults.length < 1 ) {
	    toggleVisibility( _gel( "searchList" ), false );
	    toggleVisibility( _gel( "searchBottomBar" ), false );
	    toggleVisibility( _gel( "noSearchResults" ), true );
	}
	else {
	    toggleVisibility( _gel( "searchList" ), true );
	    toggleVisibility( _gel( "searchBottomBar" ), true );
	    toggleVisibility( _gel( "noSearchResults" ), false );
	    build_search( j );
	}
    }
    else {
	showError( "onLoad_search: empty response:" );
	console.error( j );
    }
}


function onLoad_searchRaces( param_response ) 
{
    var j = getJSONFromFetch( param_response, "onLoad_searchRaces" );

    if ( j != null && j.racelist != undefined ) {
	searchRaces_array = j.racelist;

	nrInitLoads--;
	start();
    }
    else {
	showError( "onLoad_searchRaces: empty response:" );
	console.error( j );
    }
}

function onLoad_stations( param_response ) 
{
    var j = getJSONFromFetch( param_response, "onLoad_stations" );

    if ( j != null && j.stations != undefined ) {
	stations_array = j.stations;    

	nrInitLoads--;
	start();
    }
    else {
	showError( "onLoad_stations: empty response:" );
	console.error( j );
    }
}

function onLoad_topListRaces( param_response ) 
{
    var j = getJSONFromFetch( param_response, "onLoad_topListRaces" );
    
    if ( j != null && j.racelist != undefined ) {
	topListRaces_array = j.racelist;

	nrInitLoads--;
	start();
    }
    else {
	showError( "onLoad_topListRaces: empty response:" );
	console.error( j );
    }
}

function onLoadContent_news( param_result )
{
    hideLoader();

    var newsItems_array = param_result.Entry;

    if ( newsItems_array ) {
	if ( newsItems_array.length == 4 ) {
	    build_news( newsItems_array );
	}
	else {
	    showError( "onLoadContent_news: wrong nr of entries: " + newsItems_array.length );
	}
    }
    else {	
	showError( "onLoadContent_news: no entries" );
    }
}

function onLoadContent_profile( param_response ) 
{
    hideLoader();

    var j = getJSONFromFetch( param_response, "onLoadContent_profile" );

    if ( j != null && j.firstName != undefined ) {
	build_profile( j );
    }
    else {
	showError( "onLoadContent_profile: empty response:" );
	console.error( j );
    }
}

function onLoadContent_topList( param_response ) 
{
    hideLoader();

    var j = getJSONFromFetch( param_response, "onLoadContent_topList" );

    if ( j != null && j.topList != undefined ) {

	if ( j.stationList != undefined && j.stationList.length > 0 ) {
	    drawRaceMap( j.stationList[j.stationList.length-1].station );
	}
	else {
	    drawRaceMap( 1 );
	}

	if ( j.topList.length > 0 ) {
	    toggleVisibility( _gel( "noTopList" ), false );
	    toggleVisibility( _gel( "raceList" ), true );
	    build_topList( j.topList );
	}
	else {
	    toggleVisibility( _gel( "noTopList" ), true );
	    toggleVisibility( _gel( "raceList" ), false );
	}
    }
    else {
	showError( "onLoadContent_topList: empty response:" );
	console.error( j );
    }
}

function onLoadContent_weather( param_response ) 
{
    hideLoader();

    var j = getJSONFromFetch( param_response, "onLoadContent_weather" );

    if ( j != null && j.weatherConditions != undefined ) {
	build_weather( j.weatherConditions[0].forecast );
    }
    else {
	showError( "onLoadContent_weather: empty response:" );
	console.error( j );
    }
}

function onResize_()
{
    resizeMainMenu();
    centerMap();
    centerLoader();
}

function onSubmit_searchForm()
{
    if ( !isSearchFormEmpty() ) {
	var form = _gel( "searchForm" );
	
	var firstName = _gel( "firstName" ).value;
	var lastName = _gel( "lastName" ).value;
	var club = _gel( "club" ).value;
	var startNumber = _gel( "startNumber" ).value;
	var race = _gel( "searchRaceSelect" ).selectedIndex;
	
	doSearch( 1, firstName, lastName, club, startNumber, race );
    }
    else {
	updateSearchSubmit();
    }
}

function resizeMainMenu()
{
    var contentWidth = _gel( "contentHolder" ).offsetWidth;

    if ( contentWidth ) {
	var lis_array = _gel( "mainMenu" ).getElementsByTagName( "li" );
    
	var tabWidth = Math.floor( contentWidth / lis_array.length );

	for ( var loop = 0; loop < lis_array.length; loop++ ) {
	    var li = lis_array[loop];

	    if ( loop < ( lis_array.length - 1 ) ) {
		li.style.width = tabWidth;
	    }
	    else {
		li.style.width = ( contentWidth - ( ( lis_array.length - 1 ) * tabWidth ) );
	    }
	}
    }
}

function showPage ( param_tabID )
{
    var prefs = new _IG_Prefs();
    prefs.set( "lastPage", param_tabID );

    hideAllPages();
    hideLoader();

    switch ( param_tabID ) {
    case 0:
	toggleVisibility( _gel( "page_news" ), true );
	loadContent_news();
	break;
    case 1:
	toggleVisibility( _gel( "page_weather" ), true );
	loadContent_weather();
	break;
    case 2:
	toggleVisibility( _gel( "page_topList" ), true );
	initMap();
	updateTopList();
	break;
    case 3:
	toggleVisibility( _gel( "page_search" ), true );
	break;
    }
}

function showError( param_message )
{
    toggleVisibility( _gel( "errorContainer" ), true );
    console.error( param_message );
}

function showLoader()
{
    var throbber = _gel( "throbber" );
    toggleVisibility( throbber, true );

    onresize();
}

function start()
{
    if ( nrInitLoads == 0 ) {
	hideLoader();

	var prefs = new _IG_Prefs();
	var lastPage = getLastPage();
	var lastRace = getLastRace();

	initMainMenu();
	updateMainMenu( lastPage );
	initRaceSelect( lastRace );
	initNewSearchButton();
	initSearchForm();
	initSearchSelect();

	showPage( lastPage );

	onresize();
    }
}

function updateMainMenu( param_chosenTab )
{
    // mark chosen tab
    var tabMenuLis_array = _gel( "mainMenu" ).getElementsByTagName( "li" );
    for ( var loop = 0; loop < tabMenuLis_array.length; loop++ ) {
	var li = tabMenuLis_array[loop];

	if ( loop == param_chosenTab ) {
	    li.addClass( "active" );
	    if ( li.hasClass( "first" ) ) {
		li.addClass( "first-active" );
	    }
	}
	else {
	    li.dropClass( "active" );
	    if ( li.hasClass( "first" ) ) {
		li.dropClass( "first-active" );
	    }
	}
    }
}

function updateSearchSubmit()
{
    var submit = _gel( "searchSubmit" )

    if ( isSearchFormEmpty() ) {
	submit.disabled = true;
	submit.addClass( "disabledSubmit" );
    }
    else {
	submit.disabled = false;
	submit.dropClass( "disabledSubmit" );
    }
}

function updateTopList()
{
    var select = _gel( "raceSelect" );
    var index = select.selectedIndex;
    var value = select.getElementsByTagName( "option" )[index].value;

    if ( value == "none" ) {
	toggleVisibility( _gel( "noRace" ), true );
	toggleVisibility( _gel( "noTopList" ), false );
	toggleVisibility( _gel( "raceList" ), false );

	drawRaceMap( 1 );
    }
    else {
	toggleVisibility( _gel( "noRace" ), false );
	toggleVisibility( _gel( "noTopList" ), false );
	toggleVisibility( _gel( "raceList" ), false );

	loadContent_topList( value );
    }
}
